package com.qf.kdgroup.gdbackend.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.kdgroup.gdbackend.dto.ResultBean;
import com.qf.kdgroup.gdbackend.entity.User;
import com.qf.kdgroup.gdbackend.mapper.UserMapper;
import com.qf.kdgroup.gdbackend.service.UserService;
import com.qf.kdgroup.gdbackend.vo.PageVO;
import com.qf.kdgroup.gdbackend.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ResultBean findByUsername(UserVO userVO) {

        List<User> users = userMapper.findByUsername(userVO.getUsername());

        if (ObjectUtils.isEmpty(users)) {
            return ResultBean.error("用户名或密码错误");
        }

        for (User user : users) {
            if (user.getPassword().equals(userVO.getPassword())) {
                return ResultBean.success("登陆成功",user);
            }
        }

        return ResultBean.error("用户名或密码错误");

    }

    @Override
    public PageInfo selectAllByPage(PageVO pageVO) {
        PageHelper.startPage(pageVO.getPageNum().intValue(), pageVO.getPageSize().intValue());
        List<User> users = userMapper.findAll(pageVO.getKeyword());
        PageInfo pageInfo = new PageInfo(users);
        return pageInfo;
    }

    @Override
    public ResultBean deleteById(long userid) {
        int res = userMapper.deleteByPrimaryKey(userid);
        return res>0?new ResultBean().success():new ResultBean().error();
    }

    @Override
    public ResultBean add(User user) {
        int res = userMapper.insertSelective(user);
        return res>0?new ResultBean().success():new ResultBean().error();
    }

    @Override
    public User findById(Long userid) {
        return userMapper.selectByPrimaryKey(userid);
    }

    @Override
    public ResultBean update(User user) {
        int res = userMapper.updateByPrimaryKeySelective(user);
        return res>0?new ResultBean().success():new ResultBean().error();
    }
}
